package com.newthread.android.client;


import android.content.Context;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.*;
import com.newthread.android.bean.remoteBean.NetAccount;
import com.newthread.android.manager.iMangerService.IRemoteService;
import com.newthread.android.util.Loger;

import java.util.List;


/**
 * Created by jindongping on 14/12/9.
 * AccoutNetShared的实现者
 */
public class AccoutNetSharedClient implements IRemoteService<NetAccount> {
    private Context context;

    public AccoutNetSharedClient(Context context) {
        this.context = context;
    }

    @Override
    public void add(final NetAccount netAccount, final SaveListener saveListener) {
        querry(netAccount, new FindListener<NetAccount>() {
            @Override
            public void onSuccess(List<NetAccount> list) {
                if (list.size() == 0) {
                    netAccount.save(context, saveListener);
                } else {
                    Loger.V("用户已存在");
                }
            }

            @Override
            public void onError(int i, String s) {
                Loger.V("查询NetAccount失败，" + "失败码：" + i + "失败原因:" + s);

            }
        });
    }

    @Override
    public void update(final NetAccount netAccount, final UpdateListener updateListener) {
        querry(netAccount, new FindListener<NetAccount>() {
            @Override
            public void onSuccess(List<NetAccount> list) {
                if (list.size() != 0)
                    netAccount.update(context, list.get(0).getObjectId(), updateListener);
            }

            @Override
            public void onError(int i, String s) {
                Loger.V("查询NetAccount失败，" + "失败码：" + i + "失败原因:" + s);

            }
        });
    }


    @Override
    public void querry(NetAccount netAccount, FindListener<NetAccount> findListener) {
        BmobQuery<NetAccount> query = new BmobQuery<NetAccount>();
        query.addWhereEqualTo("studentId", netAccount.getStudentId());
        query.addWhereEqualTo("passWord", netAccount.getPassWord());
        query.findObjects(context, findListener);
    }

    @Override
    public void delete(final NetAccount netAccount, final DeleteListener deleteListener) {
        querry(netAccount, new FindListener<NetAccount>() {
            @Override
            public void onSuccess(List<NetAccount> list) {
                if (list.size() != 0)
                    netAccount.delete(context, list.get(0).getObjectId(), deleteListener);
            }

            @Override
            public void onError(int i, String s) {
                Loger.V("查询NetAccount失败，" + "失败码：" + i + "失败原因:" + s);
            }
        });
    }

}
